import { Tenant } from '../../types';
import { TenantRepository } from '../../repositories/system/TenantRepository';
import { HttpError } from '../../exceptions/HttpError';
export class TenantService {
    private tenantRepository: TenantRepository;

    constructor() {
        this.tenantRepository = new TenantRepository();
    }




    // 获取所有租户
    async getAllTenants(): Promise<Tenant[]> {
        try {
            return await this.tenantRepository.findAll();
        } catch (error: any) {
            if (error instanceof HttpError) throw error;
            throw HttpError.internalServerError(`获取租户列表失败: ${error.message}`);
        }
    }

    // 根据ID获取租户
    async getTenantById(id: string): Promise<Tenant | null> {
        try {
            return await this.tenantRepository.findById(id);
        } catch (error: any) {
            if (error instanceof HttpError) throw error;
            throw HttpError.internalServerError(`获取租户信息失败: ${error.message}`);
        }
    }

    // 创建租户
    async createTenant(tenantData: Partial<Tenant>): Promise<Tenant> {
        try {
            return await this.tenantRepository.create(tenantData);
        } catch (error: any) {
            if (error instanceof HttpError) throw error;
            throw HttpError.internalServerError(`创建租户失败: ${error.message}`);
        }
    }

    // 更新角色
    async updateTenant(id: string, tenantData: Partial<Tenant>): Promise<Tenant | null> {
        try {
            return await this.tenantRepository.update(id, tenantData);
        } catch (error: any) {
            if (error instanceof HttpError) throw error;
            throw HttpError.internalServerError(`更新租户失败: ${error.message}`);
        }
    }

    // 删除用户
    async deleteTenant(id: string): Promise<boolean> {
        try {
            return await this.tenantRepository.delete(id);
        } catch (error: any) {
            if (error instanceof HttpError) throw error;
            throw HttpError.internalServerError(`删除角色失败: ${error.message}`);
        }
    }



    // 获取角色数量
    async getRoleCount(): Promise<number> {
        try {
            return await this.tenantRepository.count();
        } catch (error: any) {
            if (error instanceof HttpError) throw error;
            throw HttpError.internalServerError(`统计租户数量失败: ${error.message}`);
        }
    }

    // 分页查询角色
    async getTenantsWithPagination(page: number = 1, limit: number = 10): Promise<{ list: Tenant[], total: number, pages: number }> {
        try {
            return await this.tenantRepository.findWithPagination(page, limit);
        } catch (error: any) {
            if (error instanceof HttpError) throw error;
            throw HttpError.internalServerError(`分页查询租户失败: ${error.message}`);
        }
    }
}